﻿/// <summary>
/// Baidu face identify demo.    We send up an img for 2 purposes.
/// 1 Add and register an user.   
///   Press  C  to upload an cam cap img which contains a face.
/// 
/// 2  This demo use baidu identify url to identify a face. We resort to a groupid and check userid among this group.
///    We take the highest score userid as the one we identified.
///    Press D  we run the identify and recognition function.
/// Press C to send up a face img and debug the result.
/// </summary>


//press "C"  to show some datas ,  like  gender
using UnityEngine;
using System.Collections;
using System.Web;
using System.Collections.Generic;



public class BaiduFaceIdentifyDemo : MonoBehaviour {

		
	Texture2D tx;

	public WebCamCap mWebCamCap;

	string resultTxt=string.Empty;

	//FaceStat[] facStats;

	public BaiduAIFaceMgr mBaiduFaceMgr;

	public GameObject DispObj;

	string groupID="FaceSet0";  //This is one group we set on baidu url.

	string tmpuserIDForUpload="CartoonGril0";
	string tmpuserInfo="A girl which is cartoonized which has a nick name Jenny";
	// Use this for initialization
	void Start () {
		tx	=new Texture2D(mWebCamCap.CamW, mWebCamCap.CamH, TextureFormat.RGB24, false);


	}

	// Update is called once per frame
	void Update () {
		Color32[] webColor=mWebCamCap.WebCameraTex.GetPixels32();


		//Press C to add an face image.
		if (Input.GetKeyDown(KeyCode.C))
		{
			if(mBaiduFaceMgr.enableIdentify)
			{
				tx.SetPixels32(webColor);
				tx.Apply();
				byte[] pngData = tx.EncodeToJPG ();
				StartCoroutine (mBaiduFaceMgr.PostImageToBaiduAI_AddUser(pngData,groupID,tmpuserIDForUpload,tmpuserInfo));

			}
			else
			{
				Debug.LogError("The last face Add user procedure  is not finished yet.");
			}
		}



		//press D to identify/recognize a face img.
		if (Input.GetKeyDown(KeyCode.D))
		{
			if(mBaiduFaceMgr.enableIdentify)
			{
				tx.SetPixels32(webColor);
				tx.Apply();
				byte[] pngData = tx.EncodeToJPG ();
				StartCoroutine (mBaiduFaceMgr.PostImageToBaiduAI_identify(pngData,groupID));

			}
			else
			{
				Debug.LogError("The last face identification  is not finished yet.");
			}
		}

		tx.SetPixels32(webColor);
		tx.Apply();

		DispObj.GetComponent<Renderer>().material.mainTexture = tx;
	}
			


	void OnGUI()
	{
		GUILayout.Label("This demo shows the use of baidu face idenfication\n");
		GUILayout.Label("Press c upload cam img to add an user");
		GUILayout.Label("Press d identify the cam img and log the result");

		GUILayout.Label("We send out web cam image to the baidu identify url\n  and retrieve the json result");
		GUILayout.Label("In script BaiduFaceDetectDemo, we write down the data telling us the score\n by which we know his identificaiton");



	}

}
